package com.highper.common.util;

import cn.dev33.satoken.context.SaHolder;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author ZhangGJ
 * @Date 2022/01/25 10:17
 */
public class ServletUtil {

    /**
     * 获取HttpServletRequest
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(
                RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 获取HttpServletResponse
     *
     * @return HttpServletResponse
     */
    public static HttpServletResponse getHttpServletResponse() {
        return ((ServletRequestAttributes) Objects.requireNonNull(
                RequestContextHolder.getRequestAttributes())).getResponse();
    }

    /**
     * 获取http请求Accept-Language
     *
     * @return String
     */
    public static String language() {
        String language = null;
        try {
            language = getHttpServletRequest().getHeader("language");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return StringUtils.isEmpty(language) ? "zh" : language;
    }

    /**
     * 设置响应
     *
     * @param response    HttpServletResponse
     * @param contentType content-type
     * @param status      http状态码
     * @param value       响应内容
     * @throws IOException IOException
     */
    public static void makeResponse(HttpServletResponse response, String contentType, int status,
            Object value) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);
        response.setStatus(status);
        response.getOutputStream().write(JSONObject.toJSONString(value).getBytes());
    }

    /**
     * 设置异常响应
     *
     * @param contentType content-type
     * @param status      http状态码
     */
    public static void makeExceptionResponse(String contentType, int status) {
        HttpServletResponse response = getHttpServletResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);
        response.setStatus(status);
    }

}
